import { View, Text, Button, Input } from '@tarojs/components'
import './index.less'
import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { orderUrl } from '../../constans'


export default function Index() {

  const [productId, setProductId] = useState<string>('');
  const [quantity, setQuantity] = useState("1");
  const [productTitle, setProductTitle] = useState<string>('')


  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: "Confirm",
    });
    const params = Taro.getCurrentInstance().router?.params
    if (params) {
      setProductId(params.productId || '')
      setProductTitle(params.productTitle || '')
    }
  }, [])


  const handleBuy = async (productId: string) => {
    const res = await Taro.request({
      url: orderUrl,
      data: {
        productId: productId,
        quantity: quantity
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      }
    })
    const result = res.data;
    if (result.code == 200) {
      Taro.showModal({
        content: '恭喜购买成功',
        success: function () {
          Taro.redirectTo({
            url: `/pages/index/result?orderId=${result.info.orderId}`
          })
        }
      });
    } else {
      Taro.showToast({
        title: result.info,
        icon: 'error'
      });
    }
  }

  const handleChange = (ele) => {
    setQuantity(ele.detail.value);
  }


  return (
    <View>
      <View>
        确认页面
      </View>
      <View className="product">
        <View className="product-item">
          <Text >商品名称：{decodeURIComponent(productTitle)}</Text>
          <View className='quantity'>
            <Text >购买数量：</Text>
            <Input
              style={{
                width: '60%',
                height: '80rpx',
                padding: '0 20rpx',
                border: '1px solid #ccc',
                borderRadius: '8rpx',
                backgroundColor: '#fff',
                fontSize: '28rpx'
              }}
              type='number'
              placeholder='输入购买数量'
              value={quantity}
              onInput={handleChange}
            />
          </View>
          
          <View style={{marginTop: '4px'}}>
            <Button  onClick={() => handleBuy(productId)} >
              确认
            </Button>
          </View>
        </View>
      </View>
      
    </View>
  )
}
